package com.algrithom.pointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * 977. 有序数组的平方
 * 
 * @author think
 */
public class Solution3 {
    
    public static void main(String[] args){
        int[] nums = new int[]{-4,-1,0,3,10};
        Solution3 solution4 = new Solution3();
        System.out.println(Arrays.toString(solution4.sortedSquares(nums)));
        System.out.println(Arrays.toString(solution4.sortedSquares2(nums)));
    }
    
    public int[] sortedSquares(int[] nums){
        Queue<Integer> queue = new PriorityQueue<>();
        for (int num : nums) {
            queue.offer(num * num);
        }
        
        List<Integer> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            list.add(queue.poll());
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
    
    /**
     *
     * @param nums
     * @return
     */
    public int[] sortedSquares2(int[] nums){
        int n = nums.length;
        int[] ans = new int[n];
        for (int i = 0, j = n - 1, pos = n - 1; i <= j;) {
            if (nums[i] * nums[i] > nums[j] * nums[j]) {
                ans[pos] = nums[i] * nums[i];
                ++i;
            } else {
                ans[pos] = nums[j] * nums[j];
                --j;
            }
            --pos;
        }
        return ans;
    }
}
